<?php
/**
 * Created by PhpStorm.
 * User: crazytang
 * Date: 15/12/4
 * Time: 10:28
 */

namespace App\Services\LogServices;
use Monolog\Handler\RotatingFileHandler;

class LogService
{
    private static function getLogger($logType='',$errorType,$dirName='')
    {
        static $loggers;

        if ($dirName == '')
            $name = "request_log";
        else
            $name = $dirName;

        if ($logType != '')
            $filename = $logType;
        else
            $filename = "info";

        $key = $name."|".$filename;

        if (!isset($loggers[$key]))
        {

            $path = \App::storagePath()."/{$name}/{$filename}.log";

/*            $path = \App::storagePath()."/{$name}";

            if (!is_dir($path))
            {
                @mkdir($path,true);
            }
            $path  .= "/{$filename}.log";*/


            //$days = \App::make('config')->get('app.log_max_files', 5);


            $logger = new \Monolog\Logger($name);

            $logger->pushHandler($handler = new RotatingFileHandler($path, 0, $errorType));
            $handler->setFormatter(new \Monolog\Formatter\LineFormatter(null, null, true, true));
            $loggers[$key] = $logger;
        }

        return $loggers[$key];
    }

    /**
     * 写入日志
     * @param string $logType 日志类型(日志文件名)
     * @param mixed $msg 日志内容信息,可以是字符串或数组
     * @param int $errorType 错误类型,请查看 \Monolog\Logger
     * @param string $dirName 日志目录, 存放在storage/$dirName/$logType.log
     */
    public  function writeToLog($logType,$msg, $errorType=\Monolog\Logger::INFO,$dirName='')
    {
        $str = '';
        if (is_array($msg))
        {
            foreach ($msg as $k=>$v) {
                $str .= "\t[{$k}]:{$v}";
            }
        }
        else
        {
            $str = (string)$msg;
        }

        $logger = self::getLogger($logType,$errorType,$dirName);

        $logger->addInfo($str);
    }



    /**
     * 写入日志 <Colin>
     * @param string $logType 日志类型(日志文件名)
     * @param mixed $msg 日志内容信息,可以是字符串或数组
     * @param int $errorType 错误类型,请查看 \Monolog\Logger
     * @param string $dirName 日志目录, 存放在storage/$dirName/$logType.log
     */
    public static function writeLog( $msg, $dirName='',$logType='info', $errorType=\Monolog\Logger::INFO)
    {
        $str = (is_array($msg)) ? json_encode($msg) : (string)$msg;

        $logger = self::getLogger($logType,$errorType,'logs/'.$dirName);

        $logger->addInfo($str);
    }
}